var express = require('express');
var router = express.Router();
var User = require('../models/user.js')

/* GET users listing. */
router.get('/', function (req, res, next) {
    console.log('Here goes the roo of website\n')
});


router.get('/reg', function (req, res) {
    res.render('reg', {
        title: '用户注册'
    })
})

router.post('/reg', function (req, res) {
    if (req.body['password-repeat'] != req.body['password']) {
        console.log('***** error *****')
        return res.redirect('/reg')
    }

    var newUser = new User({
        name: req.body.username,
        password: req.body.password
    })

    User.get(newUser.name, function (err, user) {
        if (user) {
            err = 'Username already exists.'
        }
        if (err) {
            console.log('*****' + err + ' *****')
            return res.redirect('/reg')
        }

        newUser.save(function (err) {
            if (err) {
                console.log('***** ' + err + ' *****')
                return res.redirect('/reg')
            }
            req.session.user = newUser
            console.log('***** success *****')
            res.redirect('/')
        })
    })

})


router.get('/u/:user', function (req, res) {

})

router.get('/login', islogin, function (req, res) {
    res.render('login', {
        title: '用户登录'
    })
})

router.post('/login', function (req, res) {
    User.get(req.body.username, function (err, user) {
        if (!user) {
            console.log('user not exists')
            return res.redirect('/login')
        }

        if (user.password != req.body.password) {
            console.log('password error')
        }

        req.session.user = user
        console.log('login success')
        res.redirect('/')
    })
})


router.get('/logout', function (req, res) {
    req.session = null
    console.log('logout success')
    res.redirect('/')
})


function isLogin(req, res, next) {
    if (req.session.user) {
        console.log('user has login')
        return res.redirect('/')
    }
    next()
}

function isNotLogin(req, res, next) {
    if (!req.session.user) {
        console.log('user has not login')
        return res.redirect('/login')
    }
    next()
}


module.exports = router;

